import { ref, reactive, toRefs } from 'vue'
import request from '@/utils/request.js'

// ======================================
// 1. 请求参数类型定义（严格 TypeScript 约束）
// ======================================
interface CreateTableRequest {
    tableName?: string
    databaseName?: string
    description?: string
}

interface DeleteTableRequest {
    tableId: number
}

interface GetTableRequest {
    tableId: number
}

interface UpdateTableRequest {
    tableId: number
    tableName: string // 修正：去掉引号，改为类型约束
    databaseName: string
    description?: string
}

interface GetAllColumnsRequest {
    tableId: number
}

interface GetTablesByDatabaseNameRequest {
    databaseName: string
}


// ======================================
// 2. 响应结果类型（泛型增强 + 语义化）
// ======================================
interface BaseResponse<T = any> {
    code?: number
    message?: string
    data: {
        data?: T
    };
    timestamp: number;
}

// 数据库表信息
interface TableInfo {
    tableId: number      // 响应字段名为 tableId 而非 id
    tableName: string
    databaseName: string // 新增字段
    description: string | null // 允许 null 值
    createdAt: string    // 新增创建时间字段
}

interface ColumnInfo {
    columnId: number
    tableId: number
    columnName: string
    dataType: string
    isNullable: 0|1          // 0-否 1-是
    isPrimaryKey: 0|1         // 0-否 1-是
    isForeignKey: 0|1         // 0-否 1-是
    foreignTableId: number | null
    foreignTableName: string | null
    foreignColumnName: string | null
    foreignColumnId: number | null
    description: string | null
    foreignKeyDescription: string | null
    createdAt: string
    javaType: string | null     // Java 映射类型
    tableName: string | null    // 冗余表名
    columnPosition: number       // 列位置序号
}


// ======================================
// 3. 通用请求工具（消除重复逻辑）
// ======================================
const baseRequest = async <T>(
    state: {
        loading: boolean
        error: string | null
        response: BaseResponse<T> | null
    },
    url: string,
    method: 'GET' | 'POST',
    params?: Record<string, any>, // GET 参数
    data?: Record<string, any>    // POST 请求体
): Promise<unknown> => {
    state.loading = true
    state.error = null
    state.response = null

    try {
        // 发送 HTTP 请求（使用封装的 request 工具）
        const response = await request({ url, method, params, data })
        state.response =  response.data as BaseResponse<T>
        return response
    } catch (error: any) {
        state.error = error.message || '请求失败'
        throw error // 抛出错误供上层处理
    } finally {
        state.loading = false
    }
}


// ======================================
// 4. 业务方法 & 状态管理（清晰隔离）
// ======================================
export const useTableService = () => {
    // 每个方法独立管理状态，避免混淆
    const createState = reactive({
        loading: false,
        error: null as string | null,
        response: null as BaseResponse<unknown> | null,
    })

    const deleteState = reactive({
        loading: false,
        error: null as string | null,
        response: null as BaseResponse<unknown> | null,
    })

    const getTableState = reactive({
        loading: false,
        error: null as string | null,
        response: null as BaseResponse<TableInfo> | null, // 明确响应类型
    })

    const updateTableState = reactive({
        loading: false,
        error: null as string | null,
        response: null as BaseResponse<unknown> | null,
    })

    const getAllColumnsState = reactive({
        loading: false,
        error: null as string | null,
        response: null as BaseResponse<ColumnInfo[]> | null, // 明确响应类型
    })

    const getDataBaseByDatabaseNameState = reactive({
        loading: false,
        error: null as string | null,
        response: null as BaseResponse<TableInfo[]> | null, // 明确响应类型
    })


    // -------------------- 创建数据表 --------------------
    const createTable = async (params: CreateTableRequest) => {
        return baseRequest(createState, '/database/createTable', 'POST', undefined, params)
    }

    // -------------------- 删除数据表 --------------------
    const deleteTable = async (params: DeleteTableRequest) => {
        return baseRequest(deleteState, '/database/deleteTable', 'GET', params)
    }

    // -------------------- 查询数据表（按 ID） --------------------
    const getTable = async (params: GetTableRequest) => {
        return baseRequest<TableInfo>(getTableState, '/database/getTable', 'GET', params)
    }

    // -------------------- 更新数据表 --------------------
    const updateTable = async (params: UpdateTableRequest) => {
        return baseRequest(updateTableState, '/database/updateTable', 'POST', undefined, params)
    }

    // -------------------- 获取表的所有列 --------------------
    const getAllColumns = async (params: GetAllColumnsRequest) => {
        return baseRequest<ColumnInfo[]>(getAllColumnsState, '/database/getAllColumns', 'GET', params)
    }

    // -------------------- 获取数据库的所有表 --------------------
    const getDataBaseByDatabaseName = async (params: GetTablesByDatabaseNameRequest) => {
        return baseRequest<TableInfo[]>(
            getDataBaseByDatabaseNameState,
            '/database/getDataBaseByDatabaseName',
            'GET',
            params
        )
    }


    // ======================================
    // 5. 导出响应式状态 & 方法
    // ======================================
    return {
        ...toRefs(createState),
        ...toRefs(deleteState),
        ...toRefs(getTableState),
        ...toRefs(updateTableState),
        ...toRefs(getAllColumnsState),
        ...toRefs(getDataBaseByDatabaseNameState),
        createTable,
        deleteTable,
        getTable,
        updateTable,
        getAllColumns,
        getDataBaseByDatabaseName,
    }
}
export type { BaseResponse }